<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
    <title>用户管理-XX管理系统</title>
    <!--Favicons-->
    <link href="assets/img/favicon.png" rel="icon" />
    <!--Vendor CSS Files-->
    <link
      href="assets/vendor/bootstrap/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      href="assets/vendor/bootstrap-icons/bootstrap-icons.css"
      rel="stylesheet"
    />
    <link
      href="assets/vendor/gridjs/dist/theme/mermaid.min.css"
      rel="stylesheet"
    />
    <!--Template Main CSS File-->
    <link href="assets/css/style.css" rel="stylesheet" />
  </head>
  <body>
    <!--=======Header=======-->··························
    <header id="header" class="header fixed-top d-flex align-items-center">
      <div class="d-flex align-items-center justify-content-between">
        <a href="index.html" class="logo d-flex align-items-center"
          ><img src="assets/img/logo.png" alt="" /><span
            class="d-none d-lg-block"
            >角色管理系统</span
          ></a
        ><i class="bi bi-list toggle-sidebar-btn"></i>
      </div>
      <!--End Logo-->
      <nav class="header-nav ms-auto">
        <ul class="d-flex align-items-center">
          <li class="nav-item dropdown pe-3">
            <a
              class="nav-link nav-profile d-flex align-items-center pe-0"
              href="#"
              data-bs-toggle="dropdown"
              ><img
                src="assets/img/profile-img.jpg"
                alt="Profile"
                class="rounded-circle"
              /><span class="d-none d-md-block dropdown-toggle ps-2"
                >用户名</span
              ></a
            ><!--End Profile Iamge Icon-->
            <ul
              class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile"
            >
              <li class="dropdown-header">
                <h6>部门名</h6>
                <span>角色名</span>
              </li>
              <li><hr class="dropdown-divider" /></li>
              <li>
                <a
                  class="dropdown-item d-flex align-items-center"
                  href="users-profile.html"
                  ><i class="bi bi-person"></i><span>用户设置</span></a
                >
              </li>
              <li><hr class="dropdown-divider" /></li>
              <li>
                <a class="dropdown-item d-flex align-items-center" href="#"
                  ><i class="bi bi-gear"></i><span>注销</span></a
                >
              </li>
            </ul>
            <!--End Profile Dropdown Items-->
          </li>
          <!--End Profile Nav-->
        </ul>
      </nav>
      <!--End Icons Navigation-->
    </header>
    <!--End Header--><!--=======Sidebar=======-->
    <aside id="sidebar" class="sidebar">
      <ul class="sidebar-nav" id="sidebar-nav">
        <li class="nav-item">
          <a class="nav-link collapse" href="index.html"
            ><i class="bi bi-grid"></i><span>主页</span></a
          >
        </li>
        <!--End Dashboard Nav-->
        <li class="nav-item">
          <a
            class="nav-link collapse"
            data-bs-target="#components-nav"
            data-bs-toggle="collapse"
            href="#"
            ><i class="bi bi-menu-button-wide"></i><span>系统管理</span
            ><i class="bi bi-chevron-down ms-auto"></i
          ></a>
          <ul
            id="components-nav"
            class="nav-content"
            data-bs-parent="#sidebar-nav"
          >
            <li>
              <a href="system-user.html"
                ><i class="bi bi-circle"></i><span>用户管理</span></a
              >
            </li>
            <li>
              <a href="system-role.html" class="active"
                ><i class="bi bi-circle"></i><span>角色管理</span></a
              >
            </li>
            <li>
              <a href="system-dept.html"
                ><i class="bi bi-circle"></i><span>部门管理</span></a
              >
            </li>
          </ul>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="blank.html"
            ><i class="bi bi-file-earmark"></i><span>后台模板页</span></a
          >
        </li>
        <!--End Blank Page Nav-->
      </ul>
    </aside>
    <!--End Sidebar-->
    <main id="main" class="main">
      <div class="pagetitle">
        <nav>
          <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="index.html">主页</a></li>
            <li class="breadcrumb-item">系统管理</li>
            <li class="breadcrumb-item active">角色管理</li>
          </ol>
        </nav>
      </div>
      <!--End Page Title-->
      <section class="section">
        <div class="row">
          <div class="col-lg-12">
            <class class="card"
              ><div class="card-body">
                <h5 class="card-title">用户列表</h5>
                <!--查询表单-->
                <form id="searchForm" class="row g-3 mb-3">
                  <div class="col-12 d-flex align-items-center">
                    <div class="me-2">名称:</div>
                    <div class="me-3">
                      <div class="input-group" style="width: 160px">
                        <input
                          type="text"
                          class="form-control"
                          name="name"
                          placeholder="请输入"
                        />
                      </div>
                    </div>
                    <div class="me-2">类型:</div>
                    <div class="me-3">
                      <div class="input-group" style="width: 160px">
                        <input
                          type="text"
                          class="form-control"
                          name="type"
                          placeholder="请输入"
                        />
                      </div>
                    </div>
                    <div class="me-2">启用状态:</div>
                    <div class="me-3" style="width: 200px">
                      <select name="enableState" class="form-select">
                        <option disabled selected value="">请选择</option>
                        <option value="启用">启用</option>
                        <option value="停用">停用</option>
                      </select>
                    </div>
                    <div class="me-2">
                      <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search"></i> 查询
                      </button>
                    </div>
                    <div>
                      <button type="reset" class="btn btn-secondary">
                        <i class="bi bi-arrow-repeat"></i> 重置
                      </button>
                    </div>
                  </div>
                  <div class="col-12 d-flex align-items-center">
                    <div class="me-2">数据范围:</div>
                    <div class="me-3">
                      <select name="dataScope" class="form-select">
                        <option disabled selected value="">请选择</option>
                        <option value="全局">全局</option>
                        <option value="部门">部门</option>
                        <option value="个人">个人</option>
                      </select>
                    </div>
                    <div class="me-2">部门类型:</div>
                    <div class="me-3">
                      <div class="input-group" style="width: 160px">
                        <input
                          type="text"
                          class="form-control"
                          name="deptType"
                          placeholder="请输入"
                        />
                      </div>
                    </div>
                  </div>
                </form>
                <button
                  type="button"
                  class="btn btn-sm btn-success m-1"
                  onclick="addRole()"
                >
                  角色新增
                </button>
                <div id="dataTable"></div></div
            ></class>
          </div>
        </div>
      </section>
    </main>
    <!-- 角色编辑模态框 -->
    <div class="modal fade" id="roleEditModal" tabindex="-1">
      <form id="roleEditForm" class="needs-validation" novalidate>
        <input type="hidden" class="form-control" />
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">新增角色</h5>
              <button
                type="button"
                class="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
              ></button>
            </div>

            <div class="modal-body">
              <!-- 角色表单 -->
              <form id="roleForm" class="row g-3 mb-3">
                <div class="col-12 d-flex align-items-center mb-2">
                  <div class="me-2">名称:</div>
                  <div class="me-3">
                    <div class="input-group" style="width: 160px">
                      <input
                        type="text"
                        class="form-control"
                        name="name"
                        id="name"
                        placeholder="请输入"
                        required
                      />
                    </div>
                  </div>
                  <div class="me-2">数据范围:</div>
                  <div class="me-3">
                    <div class="input-group" style="width: 160px">
                      <select
                        name="dataScope"
                        id="dataScope"
                        name="enableState"
                        class="form-select"
                        required
                      >
                        <option disabled selected value="">请选择</option>
                        <option value="全局">全局</option>
                        <option value="部门">部门</option>
                        <option value="个人">个人</option>
                      </select>
                    </div>
                  </div>
                </div>

                <div class="col-12 d-flex align-items-center mb-4">
                  <div class="me-2">部门类型:</div>
                  <div class="me-3">
                    <div class="input-group" style="width: 160px">
                      <select
                        name="deptType"
                        id="deptType"
                        name="enableState"
                        class="form-select"
                        required
                      >
                        <option disabled selected value="">请选择</option>
                        <option value="总公司">总公司</option>
                        <option value="分公司">分公司</option>
                        <option value="业务部门">业务部门</option>
                        <option value="其它">其它</option>
                      </select>
                    </div>
                  </div>
                  <div class="me-2">备注:</div>
                  <div class="me-3">
                    <div class="input-group" style="width: 160px">
                      <input
                        type="text"
                        class="form-control"
                        name="remark"
                        id="remark"
                        placeholder="请输入"
                      />
                    </div>
                  </div>
                </div>

                <!-- 权限分配区域 -->
                <div class="d-flex">
                  <!-- 用户管理 -->
                  <div class="card" style="width: 260px">
                    <div class="card-header d-flex justify-content-between">
                      <div>用户管理</div>
                      <div>
                        <input type="checkbox" id="userSelectAll" /> 全选
                      </div>
                    </div>
                    <div class="card-body" style="padding-top: 20px">
                      <div class="row">
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="userOption"
                            class="user-checkbox"
                            value="DEPT_QUERY"
                          />
                          查询用户
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="userOption"
                            class="user-checkbox"
                            value="DEPT_CREATE"
                          />
                          新增用户
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="userOption"
                            class="user-checkbox"
                            value="DEPT_UPDATE"
                          />
                          编辑用户
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="userOption"
                            class="user-checkbox"
                            value="DEPT_DELETE"
                          />
                          删除用户
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 部门管理 -->
                  <div class="card" style="width: 260px">
                    <div class="card-header d-flex justify-content-between">
                      <div>部门管理</div>
                      <div>
                        <input type="checkbox" id="deptSelectAll" /> 全选
                      </div>
                    </div>
                    <div class="card-body" style="padding-top: 20px">
                      <div class="row">
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="deptOption"
                            class="dept-checkbox"
                            value="ROLE_QUERY"
                          />
                          查询部门
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="deptOption"
                            class="dept-checkbox"
                            value="ROLE_CREATE"
                          />
                          新增部门
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="deptOption"
                            class="dept-checkbox"
                            value="ROLE_UPDATE"
                          />
                          编辑部门
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="deptOption"
                            class="dept-checkbox"
                            value="ROLE_DELETE"
                          />
                          删除部门
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 权限管理 -->
                  <div class="card" style="width: 260px">
                    <div class="card-header d-flex justify-content-between">
                      <div>权限管理</div>
                      <div>
                        <input type="checkbox" id="permSelectAll" /> 全选
                      </div>
                    </div>
                    <div class="card-body" style="padding-top: 20px">
                      <div class="row">
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="permOption"
                            class="perm-checkbox"
                            value="PERM_QUERY"
                          />
                          权限查询
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="permOption"
                            class="perm-checkbox"
                            value="PERM_CREATE"
                          />
                          权限新增
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="permOption"
                            class="perm-checkbox"
                            value="PERM_UPDATE"
                          />
                          权限编辑
                        </div>
                        <div class="col-6 mb-2">
                          <input
                            type="checkbox"
                            name="permOption"
                            class="perm-checkbox"
                            value="PERM_DELETE"
                          />
                          权限删除
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </form>
            </div>

            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                name="close"
                data-bs-dismiss="modal"
              >
                取消
              </button>
              <button type="submit" class="btn btn-primary" id="submit">
                确定
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
    <!--End#main--><!--=======Footer=======-->
    <footer id="footer" class="footer">
      <div class="copyright">
        &copy;Copyright<strong><span>XX管理系统</span></strong
        >.All Rights Reserved
      </div>
      <div class="credits">
        Designed by 2022030102078钟乐怡<a href="https://bootstrapmade.com/"
          >BootstrapMade</a
        >
      </div>
    </footer>
    <!--End Footer--><a
      href="#"
      class="back-to-top d-flex align-items-center justify-content-center"
      ><i class="bi bi-arrow-up-short"></i></a
    ><!--Vendor JS Files-->
  </body>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/gridjs/dist/gridjs.umd.js"></script>
  <script src="assets/vendor/gridjs/I10n/dist/l10n.umd.js"></script>
  <script src="assets/vendor/moment/moment.js"></script>
  <!--Template Main JS File-->
  <script src="assets/js/main.js"></script>
  <script>
    function addQueryParam(url, param) {
      let separator = url.indexOf("?") !== -1 ? "&" : "?";
      return url + separator + param;
    }

    const url = "/api/rest/role/all";
    const columns = [
      { id: "id", hidden: true },
      { id: "name", name: "名称" },
      { id: "type", name: "类型" },
      { id: "dataScope", name: "数据范围" },
      { id: "deptType", name: "部门类型" },
      { id: "enableState", name: "状态" },
      { id: "remark", name: "备注" },
      { id: "updateAt", name: "更新时间" },
      {
        name: "操作",
        width: "25%",
        formatter: (cell, row) => {
          const enableState = row.cells[5].data;
          const index = row.cells[0].data;
          const toggleButtonHtml =
            enableState === "启用"
              ? `<button id="roleDisableBtn" type="button" class="btn btn-sm btn-danger m-1" data-index="${index}">
              <i class="bi bi-person-slash"></i>停用
              </button>`
              : `<button id="roleEnableBtn" type="button" class="btn btn-sm btn-success m-1" data-index="${index}">
              <i class="bi bi-person-check"></i>启用
              </button>`;

          return gridjs.html(`
            <button id="rolePermissionBtn" type="button" class="btn btn-sm btn-primary m-1" data-index="${index}">
              <i class="bi bi-gear-fill"></i>权限
            </button>
            <button id="roleEditBtn" type="button" class="btn btn-sm btn-warning m-1" data-index="${index}">
              <i class="bi bi-pencil-square"></i>编辑
            </button>
            ${toggleButtonHtml}
          `);
        },
      },
    ];
    const pagination = {
      limit: 10,
      server: {
        url: (prev, page, limit) =>
          addQueryParam(prev, `size=${limit}&page=${page}`),
      },
    };

    // 获取数据函数
    async function fetchData(url) {
      try {
        const response = await fetch(url);
        const result = await response.json();
        return result;
      } catch (error) {
        console.error("Error fetching data:", error);
        return null;
      }
    }

    // 转换数据格式函数
    function transformData(data) {
      return data.map((item) => [
        item.id,
        item.name,
        item.type,
        item.dataScope,
        item.deptType,
        item.enableState,
        item.remark,
        item.updateAt
          ? moment(item.updateAt).format("YYYY-MM-DD hh:mm:ss")
          : "",
      ]);
    }

    // 渲染表格函数
    function renderTable(data) {
      const server = {
        url,
        then: () => transformData(data),
        total: (data) => data.totalElements,
      };

      const options = {
        columns,
        server,
        pagination,
        language: gridjs.l10n.cnCN,
      };

      const grid = new gridjs.Grid(options);
      grid.render(document.getElementById("dataTable"));

      // 操作按钮绑定事件
      document
        .getElementById("dataTable")
        .addEventListener("click", function (event) {
          if (event.target?.getAttribute("data-index")) {
            const index = parseInt(event.target.getAttribute("data-index") - 1);
            if (event.target.getAttribute("id") == "rolePermissionBtn") {
              permissions(data[index]);
            }
            if (event.target.getAttribute("id") == "roleEditBtn") {
              editRole(data[index]);
            }
            if (
              event.target.getAttribute("id") == "roleDisableBtn" ||
              event.target.getAttribute("id") == "roleEnableBtn"
            ) {
              toggleRoleState(data[index]);
            }
          }
        });

      return grid;
    }

    // 为全选复选框添加事件监听器
    function bindSelectAll(selectAllCheckbox, relatedCheckboxes) {
      selectAllCheckbox.addEventListener("change", function () {
        relatedCheckboxes.forEach(function (checkbox) {
          checkbox.checked = selectAllCheckbox.checked;
        });
      });

      relatedCheckboxes.forEach(function (checkbox) {
        checkbox.addEventListener("change", function () {
          const allChecked = Array.from(relatedCheckboxes).every(function (
            checkbox
          ) {
            return checkbox.checked;
          });
          selectAllCheckbox.checked = allChecked;
        });
      });
    }

    // 获取选中的权限列表
    function getSelectedPermissions() {
      const selectedPermissions = [];
      // 仅获取 class 以 "-checkbox" 结尾的复选框
      document
        .querySelectorAll('input[class$="-checkbox"]:checked')
        .forEach(function (checkbox) {
          if (checkbox.value) {
            selectedPermissions.push(checkbox.value);
          }
        });
      return selectedPermissions;
    }

    // 更新权限方法
    function renderPermissions(permissions) {
      permissions.forEach(function (permission) {
        // 选择对应权限复选框
        const checkbox = document.querySelector(`input[value="${permission}"]`);
        if (checkbox) {
          checkbox.checked = true;
        }
      });
    }
    function initPermissions() {
      const checkboxList = document.querySelectorAll(`input[type="checkbox"]`);
      checkboxList.forEach(function (checkbox) {
        checkbox.checked = false;
      });
    }

    // 初始化模态框
    function initModal(title, data = {}) {
      // modal初始化
      let roleEditDOM = document.getElementById("roleEditModal");

      // 表单初始化
      roleEditDOM.querySelector("#name").value = "";
      roleEditDOM.querySelector("#dataScope").value = "";
      roleEditDOM.querySelector("#deptType").value = "";
      roleEditDOM.querySelector("#remark").value = "";
      initPermissions();

      // 人员权限初始化
      if (JSON.stringify(data) != "{}") {
        console.log(data);

        // 权限初始化
        if ("authorities" in data) {
          renderPermissions(data.authorities);
        }
        roleEditDOM.querySelector("#name").value = data.name;
        roleEditDOM.querySelector("#dataScope").value = data.dataScope;
        roleEditDOM.querySelector("#deptType").value = data.deptType;
        roleEditDOM.querySelector("#remark").value = data.remark;
      }
      // 标题初始化
      roleEditDOM.querySelector("h5").innerText = title;
      let roleEditModal = new bootstrap.Modal(roleEditDOM, {
        keyboard: false,
      });

      // 获取表单数据方法
      function getFormData() {
        return {
          name: roleEditDOM.querySelector("#name").value,
          dataScope: roleEditDOM.querySelector("#dataScope").value,
          deptType: roleEditDOM.querySelector("#deptType").value,
          remark: roleEditDOM.querySelector("#remark").value,
          authorities: getSelectedPermissions(),
        };
      }

      return { roleEditModal, roleEditDOM, getFormData };
    }

    // 新增角色
    function addRole() {
      let { roleEditModal, roleEditDOM, getFormData } = initModal("新增角色");
      roleEditModal.show();

      roleEditDOM.addEventListener("click", function (event) {
        if (event.target.id == "submit") {
          console.log("提交数据");
          let formData = getFormData();
          fetch(`/api/rest/role`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(formData),
          }).then((response) => {
            if (response.ok) {
              // 关闭模态窗
              roleEditModal.hide();
              window.location.reload();
            } else {
              alert("提交失败,请检查表单内容");
            }
          });
        }
      });
    }

    // 权限
    function permissions(rowData) {
      let { roleEditModal, roleEditDOM } = initModal("权限", rowData);
      roleEditModal.show();
    }

    // 编辑角色
    function editRole(rowData) {
      let { roleEditModal, roleEditDOM, getFormData } = initModal(
        "编辑角色",
        rowData
      );
      roleEditModal.show();
      roleEditDOM.addEventListener("click", function (event) {
        if (event.target.id == "submit") {
          console.log("提交数据");
          let formData = getFormData();
          fetch(`/api/rest/role/${rowData.id}`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(formData),
          }).then((response) => {
            if (response.ok) {
              // 关闭模态窗
              roleEditModal.hide();
              window.location.reload();
            }
          });
        }
      });
    }

    // 启用/停用账户
    function toggleRoleState(rowData) {
      fetch(`/api/rest/role/${rowData.id}/toggle`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
      }).then((response) => {
        if (response.ok) {
          // 关闭模态窗
          window.location.reload();
        } else {
          alert("提交失败,请检查表单内容");
        }
      });
    }

    window.onload = async function () {
      // 获取表格数据
      const initialData = await fetchData(url);
      if (initialData) {
        renderTable(initialData);
      }

      // 获取全选复选框和子选框
      const userSelectAll = document.getElementById("userSelectAll");
      const userCheckboxes = document.querySelectorAll(".user-checkbox");

      const deptSelectAll = document.getElementById("deptSelectAll");
      const deptCheckboxes = document.querySelectorAll(".dept-checkbox");

      const permSelectAll = document.getElementById("permSelectAll");
      const permCheckboxes = document.querySelectorAll(".perm-checkbox");

      bindSelectAll(userSelectAll, userCheckboxes);
      bindSelectAll(deptSelectAll, deptCheckboxes);
      bindSelectAll(permSelectAll, permCheckboxes);

      const roleEditForm = document.getElementById("roleEditForm");
      // 禁止表单默认提交行为
      roleEditForm.addEventListener("submit", function (event) {
        event.preventDefault();
      });
    };
  </script>
</html>
